package com.hzjh.base.utils.other

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle

object JHAppStateManager {
    var resumeActivityCount = 0 // 处于resume状态的Activity数量
    private var isAppLaunched = false //true表示APP已启动
    fun init(application: Application,
             appLaunch: (() -> Unit)? = null, //app启动时回调
             appTurnIntoForeground: (() -> Unit)? = null, //app进入前台时回调
             appTurnIntoBackGround: (() -> Unit)? = null, //app进入后台时回调
         ) {
        application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {

            }

            override fun onActivityStarted(activity: Activity) {
                if (resumeActivityCount == 0) {
                    // 如果首次进入前台，即APP启动
                    if(!isAppLaunched){
                        isAppLaunched = true
                        appLaunch?.invoke()
                    }else{
                        appTurnIntoForeground?.invoke()
                    }
                }
                resumeActivityCount++
            }

            override fun onActivityResumed(p0: Activity) {
            }

            override fun onActivityPaused(p0: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
                resumeActivityCount--
                //同步获取其它进程状态数量
                if (resumeActivityCount == 0) {
                    // APP进入后台
                    appTurnIntoBackGround?.invoke()
                }
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {

            }

            override fun onActivityDestroyed(p0: Activity) {

            }
        })
    }

    //app 是否在后台运行
    fun isAppTurnIntoBackGround():Boolean{
        return resumeActivityCount == 0
    }
}